C++抽象类参数错误解决方法
C++ abstract class parameter error workaround
下面的代码片段产生一个错误:
#include <iostream>
using namespace std;
class A
{
public:
virtual void print() = 0;
};
void test(A x) // ERROR: Abstract class cannot be a parameter type
{
cout << "Hello" << endl;
}
除了更换之外,是否有解决此错误的方法
virtual void print() = 0;
带有
virtual void print() = { }
编辑:我希望能够通过使用多态性(即A* x = new B() ; test(x);
)传递任何扩展/实现基类A的类作为参数
干杯
由于无法实例化抽象类,因此按值传递几乎肯定是一个错误;您需要通过指针或引用传递它:
void test(A& x) ...
或
void test(A* x) ...
传递值将导致对象切片,几乎可以保证会产生意外(以糟糕的方式)后果,因此编译器将其标记为错误。
当然,更改签名:
void test(A& x)
//or
void test(const A& x)
//or
void test(A* x)
您的版本不起作用的原因是A
类型的对象在逻辑上没有意义。它很抽象。传递引用或指针会绕过这一点,因为作为参数传递的实际类型不是A
,而是A
的实现类(派生的具体类)。
要绝对清楚,问题是,无论何时定义类:
#include <iostream>
class foo {
public:
char *name = (char *)"foo";
};
并将该类的实例传递给函数,它将创建一个副本:
void bar(foo a) {
a.name = (char *)"bar";
}
int main() {
foo x;
bar(x);
std::cout << x.name << std::endl; // foo
return 0;
}
关于继承,它创建一个副本作为基类的实例:
#include <iostream>
class foo {
public:
char *name = (char *)"foo";
};
class bar: public foo {
public:
char *name = (char *)"bar";
};
void baz(foo a) {
std::cout << a.name << std::endl;
}
int main() {
bar x;
baz(x); // again, foo
return 0;
}
因此,通过进行
void baz(AbstractType a) {
...
}
您告诉编译器将AbstractType
复制为AbstractType
本身的实例,这是非法的。将其作为const AbstractType &a
传递以防止复制。
相关文章:
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 从 int 中剥离位时,编译器会警告一个转换,但不警告其他转换.有解决方法吗?
- 是否有解决方法可以在 c++ 中为 short 定义用户定义的文字?
- 不为 emplace() 定义构造函数的解决方法
- 删除复制构造函数的 Intel 13.1.2 中不良C++行为的解决方法
- 函数模板部分专业化-有什么解决方法吗
- 带boost的过载模糊性:可选,解决方法
- 继承构造函数和其他变量的解决方法
- C++ 解决方法:"从类型"B*"的表达式初始化类型"C*&"的引用无效"
- 对前向声明类型进行unique_ptr的解决方法
- 解决方法:'can not be used when making a shared object; recompile with -fPIC'使用Cmake。使用普通的 g++ 工作
- 解决方法:QPixmap:在GUI线程之外使用pixmap是不安全的
- CreateProcessWithTokenW 的 cmdline 参数的最大长度是否有解决方法?
- C++双精度作为模板参数的解决方法
- 在参数相关查找之前进行模板替换的任何方法(或解决方法?
- CUDA 内核"Only a single pack parameter is allowed"解决方法?
- dlsym() 解决方法返回类型
- VS2017是否有VLA(可变长度阵列)支持解决方法
- 解决方法:未定义对"class::function"的引用
- 来自 Boost 的 JSON 解析器的警告 C4512 的解决方法