在C++中練習成員賦值,您可以將一個對象的值設置爲同一個類的另一個對象。該程序的想法是用一些值初始化一個矩形對象,並創建另一個矩形對象,但將第一個值賦給第二個。C++錯誤:沒有匹配的構造函數用於初始化
它給我一個錯誤,這是貼在下面,我無法弄清楚它是什麼,它的駕駛我堅果笑
這是我Rectangle.h
#ifndef RECTANGLE_H
#define RECTANGLE_H
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double, double);
double getLength() const;
double getWidth() const;
};
Rectangle::Rectangle(double l, double w) {
length = l;
width = w;
}
double Rectangle::getWidth() const { return width; }
double Rectangle::getLength() const { return length; }
#endif
這是我的Rectangle.cpp
#include <iostream>
#include "rectangle.h"
using namespace std;
int main()
{
Rectangle box1(10.0, 10.0);
Rectangle box2;
cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
box2 = box1;
cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
return 0;
}
這是編譯時的錯誤。
skipper~/Desktop/Programming/Memberwise: g++ rectangle.cpp
rectangle.cpp:7:12: error: no matching constructor for initialization of
'Rectangle'
Rectangle box1(10.0, 10.0);
^ ~~~~~~~~~~
./rectangle.h:4:7: note: candidate constructor (the implicit copy constructor)
not viable: requires 1 argument, but 2 were provided
class Rectangle {
^
./rectangle.h:4:7: note: candidate constructor
(the implicit default constructor) not viable: requires 0 arguments, but 2
were provided
1 error generated.
編輯:這是我如何能夠使它工作。我將所有東西都移動到了rectangle.cpp中,並給出了構造函數的默認參數。
EDITED rectangle.cpp
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
//Rectangle();
Rectangle(double = 0.0, double = 0.0);
double getLength() const;
double getWidth() const;
};
int main()
{
Rectangle box1(10.0, 10.0);
Rectangle box2;
cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
box2 = box1;
cout << "box1's width and length: " << box1.getWidth() << ", " << box1.getLength() << endl;
cout << "box2's width and length: " << box2.getWidth() << ", " << box2.getLength() << endl;
return 0;
}
Rectangle::Rectangle(double l, double w) {
length = l;
width = w;
}
double Rectangle::getWidth() const { return width; }
double Rectangle::getLength() const { return length; }
只有我做出了讓默認參數到我的用戶定義構造函數的變化。但是,如果更改位於rectangle.h中,則無法工作。但是,當我將類和成員函數定義移動到rectangle.cpp時,它能夠工作。所以,我得到了該程序的工作,但我沒有解決真正的問題,這是當類和成員函數定義在rectangle.h中,它不會編譯。
如果有人遇到此問題並找到了解決辦法,請告訴我您是如何做到的。謝謝:)
因此,據我所知,無論何時我創建一個用戶定義的構造函數,我還必須創建一個默認構造函數。在C++中總是這樣嗎? – skipper
@skipper是的。但是,如果您提供默認參數,則您的用戶定義構造函數也可以是默認構造函數,因此不需要提供2個不同的構造函數。默認構造函數是允許不帶參數調用的任何構造函數。有關更多詳細信息,請參閱[此處](http://en.cppreference.com/w/cpp/language/default_constructor)。 – vsoftco