gpt4 book ai didi

C++ 将参数类型解释为构造函数

转载 作者:行者123 更新时间:2023-11-30 01:20:01 25 4
gpt4 key购买 nike

社区,

我是 C++ 的新手,所以我希望你能帮助我。我已经用Java写过,有很多相似之处,但我无法理解这个错误。看起来,在我的 PrimitiveBase.cpp 的构造函数中,编译器将 Type Color 解释为没有参数的构造函数,而我没有。当我定义第二个没有参数且没有功能的构造函数时,错误就消失了。但这与我对函数参数减速的理解不符。

她是错误的:

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/PrimitiveBase.cpp: In constructor 'PrimitiveBase::PrimitiveBase(std::vector<Coordinate>, Colour)':

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/PrimitiveBase.cpp:5:74: error: no matching function for call to 'Colour::Colour()'

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/PrimitiveBase.cpp:5:74: note: candidates are:

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/Colour.hh:9:2: note: Colour::Colour(int, int, int, std::string)

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/Colour.hh:9:2: note: candidate expects 4 arguments, 0 provided

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/Colour.hh:6:7: note: Colour::Colour(const Colour&)

/home/christian/Documents/EBV/ebv-S03-G01/src/Graphics2D/Colour.hh:6:7: note: candidate expects 1 argument, 0 provided

这里是您可能需要的代码:PrimitiveBase.cpp

#include <Graphics2D/PrimitiveBase.hh>
#include <Graphics2D/Coordinate.hh>
#include <Graphics2D/Colour.hh>

PrimitiveBase::PrimitiveBase(std::vector<Coordinate> coord, Colour colour) { //Here the error happens
this->coord=coord;
this->colour=colour;
}

Colour PrimitiveBase::GetColour() {

return colour;

}

std::vector<Coordinate> PrimitiveBase::GetCoordinates() {

return coord;

}

void PrimitiveBase::SetColour(int red, int green, int blue) {

colour.SetColours(red,green,blue);

}

void PrimitiveBase::SetCoordinates(std::vector<Coordinate> newCoord) {

coord = newCoord;

}

颜色.hh

#ifndef COLOUR_HH_
#define COLOUR_HH_

#include <string>

class Colour {

public:
Colour(int red, int green, int blue, std::string name);
//Colour(){}; Constructo I seem to need
//~Colour();
void SetColours(int red, int green, int blue);
static Colour black();
static Colour red();
static Colour green();
static Colour blue();

private:
std::string name;
unsigned char rgb[3];

};

#endif

我真的不明白,因为过去 2 年我都是用 Java 做的,在最后的练习中它也适用于 C++。

如果你能帮助我,我会很高兴:)

最佳答案

您有一个 Colour 数据成员,并且您没有在构造函数中初始化它。因此尝试调用其默认构造函数。没有默认构造函数,因此会出现编译错误。要初始化它,请使用构造函数初始化列表:

PrimitiveBase::PrimitiveBase(std::vector<Coordinate> coord, Colour colour) 
: coord(coord), colour(colour) // HERE
{

}

一旦进入构造函数体,所有实例都已被初始化,无论是隐式的还是显式的。您只能修改它们。

关于C++ 将参数类型解释为构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com