簡體   English   中英

如何在C ++ OOP中正確使用類中的函數

[英]How to use a function in class correctly in C++ OOP

抱歉這樣一個不好的頭銜。 現在請看我的詳細問題。

實際上,我遇到了這樣一個練習題:確定一個復雜數字的CComplex類。 然后,在CComplex確定兩個對象c1c2 接下來,使用構造函數初始化c1c2 之后,將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;
}

它有一個錯誤'c2' : redefinition

然后,我改變了CComplex c2(c1); 進入c2(c1);

此時,它有一個錯誤, error C2064: term does not evaluate to a function

現在,我不知道如何糾正它。

PS:我知道使用c2=c1可以直接達到目標。 但是,我真的想知道如何根據我上面的代碼進行糾正。 另外,我想知道是否有更好的方法來傳達復雜的數字。

我知道使用c2=c1可以直接實現目標

它會起作用,並且會很好地完成它的工作。 因此,我沒有看到你試圖通過更復雜(和不正確)的語法實現的目標。

是的,你不能創建c2對象而不是使用復制構造函數,因為復制構造函數創建了NEW對象,你可以直接使用它

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM