2016-02-11 49 views
-2

任務是創建類,該類在每個時刻對其類型的對象進行計數。這是我的代碼。錯誤是: 1.對象具有與成員函數「counter :: print」不兼容的類型限定符; 2.返回值類型與函數類型不匹配; - 這真是太棒了! 我糾正了錯誤,它給了我一個我無法修復的新錯誤; 1. '無效計數器::打印(無效)':不能轉換從 'const的計數器' '這個' 指針 '計數器&'在複製構造函數C++中使用print()函數

class counter { 
private: 
    static int count; 
public: 
    counter(); 
    counter(const counter &from); 
    void print() const; 
    ~counter(); 
}; 
counter::counter() { 
    ++count; 
} 
counter::counter(const counter &from) { 
    ++count; 
    cout << "Copy constructor:\t"; 
    from.print(); // here is the error 
} 
void counter::print() const{ 
    cout << "\t Number of objects = " << count << endl; 
} 
counter::~counter() { 
    --count; 
    cout << "Destructor:\t\t"; 
    print(); 
} 
int counter::count = 0; 
counter f(counter x); 
void main() { 
    counter c; 
    cout << "After constructing of c:"; 
    c.print(); 
    cout << "Calling f()" << endl; 
    f(c); 
    cout << "After calling f():"; 
    c.print(); 
} 
counter f(counter x) { 
    cout << "Argument inside f():\t"; 
    x.print(); 
    return x; 
} 
+0

'return x;'as'void'? – LogicStuff

+0

所以你已經修復了下面指出的錯誤。當你說'void counter :: print(void)'時:不能將'this'指針從'const counter'轉換爲'counter&'正確* where * this does not say this> –

回答

1

首先,變化:

void print(); 

到:

void print() const; 

因爲(a)它是一個const方法反正及(b)你想調用它在構造函數中的const上下文。

對於這裏的第二個錯誤:

void f(counter x) { 
    cout << "Argument inside f():\t"; 
    x.print(); 
    return x; // 2 - nd error 
} 

它應該是相當明顯的是,你不能從一個void函數返回一個值。無論是將其更改爲:

counter f(counter x) { 
    cout << "Argument inside f():\t"; 
    x.print(); 
    return x; 
} 

或根本不返回任何東西:

void f(counter x) { 
    cout << "Argument inside f():\t"; 
    x.print(); 
} 
0

void print();

你已經宣佈非const成員函數,這意味着它不能被const實例調用。

from.print(); // 1 - st error

這裏from類型是const counter&這意味着它不能調用print功能。而是讓你的print函數爲const。

void print() const; 
void counter::print() const { ... } 

return x; // 2 - nd error

你爲什麼從功能與void返回類型返回什麼?