相关疑难解决方法(0)

编译器是否真的强制执行纯虚析构函数?

为了验证语句" 编译器和链接器强制存在的纯虚拟析构函数的函数体. "这篇geeksforgeeks文章,我编译了这段代码:

class Base
{
public:
    virtual ~Base()=0; // Pure virtual destructor
};

class Derived : public Base
{
public:
    ~Derived()
    {
        std::cout << "~Derived() is executed";
    }
};

int main()
{
    //Derived d;   <<<
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译没有任何错误.那么为什么编译器在这种情况下没有选择强制执行函数体的存在呢?

c++ destructor compilation pure-virtual language-lawyer

2
推荐指数
1
解决办法
154
查看次数

关于工作C++ 03代码的G ++(C++ 14)链接器错误

考虑以下代码.

class aClass
{
public:
    static const int HALLO = -3;
};

int main()
{
  std::vector<double > a;
  std::vector<int> b;
  std::vector<int> c;
  int d = aClass::HALLO; //fine
  a.resize(10,aClass::HALLO); //fine
  b.resize(10,aClass::HALLO); // linker error c++11 and c++14
  c.resize(10,(int)(double)aClass::HALLO); //fine
  std::cout<<a[0]<<endl;
  std::cout<<b[0]<<endl;
  std::cout<<c[0]<<endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译与C++ 03一起使用并产生输出:

-3
-3
-3
Run Code Online (Sandbox Code Playgroud)

但是,使用C++ 11或C++ 14进行编译会导致链接器错误:

/tmp/cc3BARzY.o: In Funktion `main':
main.cpp:(.text+0x66): Nicht definierter Verweis auf `aClass::HALLO'
collect2: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

奇怪的是,这只发生在矢量上b.如果有一个强制转换为double(a)或甚至是double并返回到int(c),则代码按预期运行.

如何解释这种行为?

c++ static g++ linker-errors

2
推荐指数
1
解决办法
157
查看次数

为什么“int const B::bsm1a;” 不考虑重新定义吗?

#include <iostream>
struct B {
public:
    static int const bsm1a{ 0xf };
};
int const B::bsm1a; // 1) Why is this NOT considered a redefinition?
                    // 2) What does this line actually do here?

int main()
{
    std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)
#include <iostream>
struct B {
public:
    static int const bsm1a{ 0xf };
    static int const bsm1a; // Considered as a redefinition here and throws error C2086
};

int main()
{
    std::cout << "Hello World!\n";
}
Run Code Online (Sandbox Code Playgroud)

我的问题(嵌入在代码中):

  1. 为什么这不被视为重新定义?
  2. 这条线实际上在这里做什么?

c++ visual-studio

2
推荐指数
1
解决办法
419
查看次数

静态数据成员的地址

为什么当数据成员在类内初始化且没有类外定义时,C++ 不允许获取静态数据成员的地址?在这种情况下,静态成员的存储空间是如何分配的?

下面的最小程序演示了这个问题。

#include <iostream>

class Test {
public:
    static const int a = 99;   // how is the storage allocated for Test::a??
};

// const int Test::a;

int main() {
    std::cout << Test::a << '\n';  // OK, print 99
    const int* ptr = &Test::a;     // Linker error, undefined reference to Test::a
}
Run Code Online (Sandbox Code Playgroud)

如果我取消注释该行const int Test::a,那么程序就可以正常工作。

c++ static-members

0
推荐指数
1
解决办法
149
查看次数