c++ - C++应该使用哪个类?

标签 c++ class

我认为描述有点棘手。但我会尽力...

给定:

前卫 (Prog_A)

一个库 (Lib_A) 与 类Class_A

还有一个库 (Lib_B) 和(还有)一个类 Class_A 并且有一个成员 Class_A mClass_A

两个类 Class_A 都有函数

void Class_A::DoSome(){
...
}

然后对于 Lib_A 中的 Class_A

void Class_A::DoSome(){
std::cout << "LIB_A";
}

然后对于 Lib_B 中的 Class_A

void Class_A::DoSome(){
std::cout << "LIB_B";
}

Prog_A 包含 Lib_A,Lib_A 包含 Lib_B。 Lib_A 和 Lib_B 通过 Callback 的“连接”。 如果我现在在 Lib_B 中调用 mClass_A.DoSome() 则它正在打印

LIB_A

而不是我期望的“LIB_B”。

这种行为是否正确,还是我必须担心?

最佳答案

您的代码有误。您已定义 Class_A 两次,但定义不匹配。

这是不允许的

[C++11: 3.2/3]: Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. The definition can appear explicitly in the program, it can be found in the standard or a user-defined library, or (when appropriate) it is implicitly defined (see 12.1, 12.4 and 12.8). An inline function shall be defined in every translation unit in which it is odr-used.

[C++11: 3.2/5]: There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D` defined in more than one translation unit, then

  • each definition of D shall consist of the same sequence of tokens;
  • [..]

如果您直接构建整个程序,您会在链接时遇到多重定义错误;但是,由于您是动态链接,所以这是不可能的,您的程序完全损坏了。

使用 namespace 将定义彼此分开。

我在使用 a custom boost::lexical_cast specialisation I'd found on Stack Overflow 时不小心导致了一次这个问题在共享库中,没有意识到原来的“默认”特化已在单独的共享库中实例化。我从主应用程序获得的行为是非常不可预测的。

关于c++ - C++应该使用哪个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29347717/

相关文章:

c++ - 在 C++ 中重载 [] 运算符

c++ - 包含二维数组的类的运算符重载

c++ - 为什么在我的光线追踪器中计算阴影和反射时会丢失细节

java - 创建 Lambda 函数实例

jquery - 如何在 jQuery 中获取具有特定类名的 <span> 元素?

c++ - 通过从 std::function 隐式转换从 nullptr_t 到类型的转换

c++ - c++中引用的使用

php - 无法从 $class 获取静态变量

php - 了解 PHP 中的类

c++ - 可以在 C++ 中调用缺少模板参数的模板函数吗?