【发布时间】:2018-09-24 13:10:13
【问题描述】:
我正在尝试创建一个具有两个值的类“Apple” 1.int n 2. 枚举颜色
但我的代码不起作用,并且出现“初始化没有匹配的构造函数”错误
我不知道最好的方法是什么。
#include <iostream>
#include<stdexcept>
using namespace std;
class Color{
public:
enum color{r,g};
};
class Apple: public Color {
int n;
Color c;
public:
Apple(int n,Color color){
if(n<0)throw runtime_error("");
this->n=n;
this->c=color;
}
int n_return(){return n;}
};
int main(){
try{
const Apple a1{10,Color::g};
cout << a1.n_return();}
catch(runtime_error&){
cout<<"ER\n";
}
return 0;
}
我不想更改 main 中的任何内容。
另外,如果没有给定颜色,如何在构造函数中将苹果的默认颜色设置为g?
【问题讨论】:
-
Apple继承并包含Color(顺便说一句,这是空类)? -
enum class Color { red, green }; -
Color!=Color::color. -
让 Apple 继承 Color 是没有意义的。苹果有一种颜色,但它们不是颜色。