为什么一个代码编译了,另一个却失败了

why does one code compiles and the other fails?

本文关键字:另一个 失败 编译 代码 一个 为什么      更新时间:2023-10-16

此代码符合:

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);
}

我得到这个错误:

错误C2558:类"SharedPointer":没有可用的复制构造函数或复制构造函数被声明为"显式"

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

#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;也是一个好主意。)

您的复制构造函数声明了

SharedPointer(SharedPointer<T>& sp);

应该看起来像:

SharedPointer(const SharedPointer<T>& sp);

因此编译器将找到丢失的复制构造函数