1

私はclass Student( studentOwner) とを持っていclass Sectionます。これが私のクラスStudentです:

class Student {
  vector<Section*> enrolledSections;
public:
  vector<Section*> getEnrolledSections() const { return enrolledSections; }
}

そのため、別のベクトルを取得vector<Section*>して割り当てると、エラーが発生します。Microsoft Visual Studio を使用しています。

// first example: no error, if take size of vector
int a = studentOwner->getEnrolledSections().size();
// second example: error, when only take its vector and assign again
// Error: no suitable user-define conversion from "std::vector<error-type" ....
vector<Section*> enrolled = studentOwner->getEnrolledSections();
// third example: error when take this vector and assign to reference of same type
// Error: initial value of reference to non-const value must be lvalue
vector<Section*>& enrolled = studentOwner->getEnrolledSections();

2 番目の例の完全なエラーは次のとおりです。

Error: no suitable user-define conversion from "std::vector<error-type", std::alocator<<error-type> *>> "to " std::vector<Section*, std::allocator<Section*>>" exists

私のプロジェクトの多くのクラスで、2行目と3行目を実行できず、同じエラーが発生しました。自分では説明できません。この際教えてください。

ありがとう :)

4

2 に答える 2

3

通常error-type、MSVC エラーが表示される場合は、そのコンパイル ユニットに間に合わなかった前方宣言型の結果です。例えば、

// Course.h
class Student;

class Course {
     [...]
public:
     Student* getStudent();
}

// Course.cpp
#include "Course.h"

Student* Course::getStudent()
{
    return new Student("Name");  //< Whoops, we never included Student.h!
}

コメントでは、循環インクルード依存関係を示しています。@Daniel Castro が指摘したように、ヘッダー ファイルで前方宣言を行って循環インクルードを回避し、必要なヘッダー ファイルを .cpp ファイルに含める必要があります (class Student;慣れていない場合は、上記の前方宣言に注意してください)。

余談ですが、あなたの例にはいくつかの設計上の問題もあります。戻ってきstd::vector<Section*>ても、誰が何を所有しているかについてはあまりわかりません。関数から by 値を取得した場合std::vector、規則では、ベクターとその内容を所有することになります。私が何かを所有している場合は、それを削除する責任があります。実際の実装を見なくても、ほとんどのコーダーは、ベクターの内容を削除してはならないことを知って驚くでしょう。const&クライアント コードがベクトルを操作できないようにする (例: )によってベクトルを返す(クライアントがベクトルを所有const vector<Section*>&しないようにする) か、std::shared_ptrを使用してオブジェクトの共有所有権スキームを管理することをお勧めします。Section

class Student {
    vector<shared_ptr<Section>> enrolledSections_;
public:
    vector<shared_ptr<Section>> getEnrolledSections() const { return enrolledSections_; }
}

これで、誰が何を所有しているかが明確になりました。あなたが求めていた以上のものですが、うまくいけば役に立ちます。

于 2012-11-22T04:49:58.417 に答える
0

ベクトルを参照として返す必要があります。そうしないと、返されたときにベクトルがコピーされます。また、関数は const であるため、ベクトルも const として返す必要があります。

class Student 
{
  std::vector<Section*> enrolledSections;
public:
  const std::vector<Section*> &getEnrolledSections() const { return enrolledSections; }
}

今、あなたはできるはずです

const std::vector<Section*>& enrolled = studentOwner->getEnrolledSections();
于 2012-11-22T03:53:00.017 に答える