c++ - 为什么一个代码编译而另一个失败?

标签 c++

此代码符合:

template <class T>
class A {};

void main () {

    A<int> a;
    vector<A<int>> vec;
    vec.push_back(a);
}

但这不是:

void main () {

    SharedPointer<int> sp;
    vector<SharedPointer<int>> vec;
    vec.push_back(sp);
}

我收到这个错误:

error C2558: class 'SharedPointer' : no copy constructor available or copy constructor is declared 'explicit'

SharedPointer header :(所有方法都在 header 中实现)

#include <iostream>
#include "Myexception.h"
using namespace std;

#pragma once

template<class T>
class SharedPointer {
    T* ob;
    int* refcount;
    bool shareable;

    int refdown();
    int refup();
    void markUnshareable();
public:

    virtual ~SharedPointer();
    SharedPointer():shareable(true);
    SharedPointer(T pointee):shareable(true);
    SharedPointer(SharedPointer<T>& sp);
    SharedPointer operator=(const SharedPointer<T>& sp);
    bool operator==(const SharedPointer<T>& sp);
    const T& operator[](const int idx) const;
    T& operator[](const int idx);
    T* operator->() const;
    T& operator*() const;
    void setOb(T pointee);
    const T& getOb() const;
    int getRefcount();
    bool isShareable();
    bool isShared();
};

最佳答案

问题在于复制构造函数:

SharedPointer(SharedPointer<T>& sp);

不能仅用于复制 const 指针。添加缺少的 const,一切都应该没问题:

SharedPointer(const SharedPointer& sp);   // <T> is harmless, but unnecessary

(您还必须修复构造函数定义中的语法错误,并且您应该将 main 的返回类型更改为 int。删除 using namespace std; 也是一个好主意。)

关于c++ - 为什么一个代码编译而另一个失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23272769/

相关文章:

c++ - 具有两个可以采用多种不同类型的操作数的虚函数

c++ - 混合多个lex/yacc组合

c++ - qt - 如何通过 http 下载和保存图像?

c++ - 如何修复这段充斥着模板的代码中的语法?

c++ - 在不转换对象的情况下调用子类方法

c++ - 通过作为 C++ 中函数的指针传递来访问 std::array 元素的正确方法是什么?

c++ - 在 C 代码中使用 #define nullptr 有什么缺点吗?

c++ - Windows 中的 gdb : different behaviour when debugging compiled C and C++ code

c++ - C++ 中的非限定查找

c++ - 抽象基类定义