C++ 如何在C++;哎呀

C++ 如何在C++;哎呀,c++,oop,class,C++,Oop,Class,很抱歉这个标题不好。现在请看我的详细问题 实际上,我面临着这样一个练习问题:为复数定义一个类CComplex。然后,在CComplex中确定两个对象c1和c2。接下来,使用构造函数初始化c1和c2。然后,将c1的值赋给c2 我的代码如下: #include<iostream> using namespace std; class CComplex { public: CComplex(int real1,int image1) { real=real

很抱歉这个标题不好。现在请看我的详细问题

实际上,我面临着这样一个练习问题:为复数定义一个类
CComplex
。然后,在
CComplex
中确定两个对象
c1
c2
。接下来,使用构造函数初始化
c1
c2
。然后,将
c1
的值赋给
c2

我的代码如下:

#include<iostream>
using namespace std;

class CComplex
{
public:
    CComplex(int real1,int image1)
    {
        real=real1;
        image=image1;
    }
    CComplex(CComplex &c)
    {
        real=c.real;
        image=c.image;
    }
public:
    void Display(void)
    {
        cout<<real<<"+"<<image<<"i"<<endl;
    }
private:
    int real,image;
};

int main()
{
    CComplex c1(10,20);
    CComplex c2(0,0);
    c1.Display();
    c2.Display();
    CComplex c2(c1);
    c2.Display();
    return 0;
}
#包括
使用名称空间std;
类C复合体
{
公众:
CComplex(int real1,int image1)
{
real=real1;
图像=图像1;
}
CComplex(CComplex&c)
{
real=c.real;
image=c.image;
}
公众:
作废显示(作废)
{
库特
我知道使用
c2=c1
可以直接实现目标


它会工作,并且会出色地完成它的工作。因此,我看不出您试图用更复杂(且不正确)的语法实现什么。

是的,您不能创建c2对象,而不能在其上使用复制构造函数,因为复制构造函数创建新对象,所以您可以直接使用它

CComplex c1(10,20);
c1.Display();
CComplex c2(c1);
c2.Display();
要将c2创建为c1的副本,或者如果要将值指定给对象,请使用类似以下内容:

CComplex c1(10,20);
CComplex c2(0,0);
c1.Display();
c2.Display();
c2=c1;
c2.Display();
此外,您还应为此目的提供自己的派遣运营商

    CComplex& operator=(const CComplex& other){
    if (this != &other) // protect against invalid self-assignment
    {
        // possible operations if needed:
        // 1: allocate new memory and copy the elements
        // 2: deallocate old memory
        // 3: assign the new memory to the object

    }
    // to support chained assignment operators (a=b=c), always return *this
    return *this;
    }

我不确定你的目标到底是什么,因为你已经知道了正确的答案。然而,也许这个“看起来”更像是你的错误版本,对你来说更好

c2 = CComplex(c1);

您有
ccomplexc2(0,0);
然后是
ccomplexc2(c1)
-这声明了一个同名的新对象,编译器会抱怨。
c2=c1
是正确的方法,否则您必须删除第一个声明。这可能会有点帮助。而且,您的练习问题本身误导了您。您不能声明一个对象并在以后构造该对象。我拒绝告诉您定义了
operator()
因为你应该只使用
操作符=
。传递复数的更好方法是使用
std::complex
@AlexChamberlain
操作符()
的含义是什么?函数?这个答案是错误的,因为他需要调用
Display()
c2
上,然后他用
c1
的值重新赋值。是的,你现在这样做了,因为你已经编辑了答案!我在发布时的评论是准确的。是的!你明白我的意思了。现在,我仍然可以使用
CComplex(CComplex&c)
。但是,我知道
c2=c1
是最好的。