#include<iostream>
using namespace std;
class circle{
public:
circle();
circle(int x,int y,int r);
void display();
~circle(){
cout<<"Destructor called";
}
private:
int x1,y1,r1;
};
circle::circle():x1(0),y1(0),r1(10){
cout<<"Defalut constructor called"<<endl;
}
circle::circle(int x,int y,int r):x1(x),y1(y),r1(r){
cout<<"Constructor called";
}
void circle::display(){
cout<<"半径为"<<r1<<" "<<"面积为"<<r1*r1<<endl;
}
int main()
{
circle circle1;
circle circle4(20,20,10);
circle1=cricle4;
circle circle2(3,4,5);
circle circle3(circle2);
circle circle2(3,4,30);
circle circle3.display();
将第一个圆的圆心改为(20,20)的问题。你可以通过以下方式修改:
main
函数中,直接修改 circle1
对象的圆心位置。circle
类中,添加一个公有成员函数用于设置圆心位置。下面是修正后的代码:
#include<iostream>
using namespace std;
class circle {
public:
circle();
circle(int x, int y, int r);
circle(const circle& other);
void display();
void setCenter(int x, int y); // 添加设置圆心位置的函数
~circle() {
cout << "Destructor called" << endl;
}
private:
int x1, y1, r1;
};
circle::circle() : x1(0), y1(0), r1(10) {
cout << "Default constructor called" << endl;
}
circle::circle(int x, int y, int r) : x1(x), y1(y), r1(r) {
cout << "Constructor called" << endl;
}
circle::circle(const circle& other) : x1(other.x1), y1(other.y1), r1(other.r1) {
cout << "Copy constructor called" << endl;
}
void circle::display() {
cout << "半径为" << r1 << " " << "面积为" << r1 * r1 << endl;
}
void circle::setCenter(int x, int y) {
x1 = x;
y1 = y;
}
int main() {
circle circle1;
circle circle4(20, 20, 10);
circle1 = circle4;
circle1.setCenter(20, 20); // 将第一个圆的圆心位置设定为 (20,20)
circle circle2(3, 4, 5);
circle circle3(circle2);
circle2.display();
circle3.display();
return 0;
}
注意,我还添加了一个拷贝构造函数,以及在 circle
类中添加了 setCenter
函数用于设置圆心位置。你可以运行这个修正后的代码,并查看运行结果截图,以确认它的正确性。
参考如下:
#include<iostream>
using namespace std;
class circle
{
public:
circle();
circle(int x,int y,int r);
~circle()
{
cout<<"Destructor called"<<endl;
}
void setPosition(int x, int y);
void setRadius(int r);
void display();
private:
int x,y,r;
};
circle::circle():x(0),y(0),r(10)
{
cout<<"Defalut constructor called"<<endl;
}
circle::circle(int x,int y,int r):x(x),y(y),r(r)
{
cout<<"Constructor called"<<endl;
}
void circle::setPosition(int x, int y)
{
this->x = x;
this->y = y;
}
void circle::setRadius(int r)
{
this->r = r;
}
void circle::display()
{
cout<<"半径为"<<r<<" "<<"面积为"<<r*r<<endl;
}
int main()
{
circle circle1;
circle circle2(20,20,10);
circle circle3 = circle2;
circle1.setPosition(20, 20);
circle2.setRadius(30);
circle3.display();
}