[英]C++ - error: 'function' was not declared in this scope
我有以下問題:錯誤:在此范圍內未聲明'kleiner'我的教授告訴我,我的代碼對他而言還行。 目錄全部包含在bulid選項中(我正在使用Code :: Blocks)。 有人可以告訴我可能是什么問題嗎?
main.cpp中
#include <iostream>
#include "vector.h"
using namespace std;
int main(int argc, char *argv[])
{
Vector v1;
cout << "v1: " << v1 << endl;
Vector v2(8);
cout << "v2: " << v2 << endl;
cout << "Minimum von v2: " << v2.min() << endl;
Vector v3(v2);
cout << "v3: " << v3 << endl;
cout << "Anzahl von v3: " << v3.getAnzahl() << endl;
if ( kleiner( v3[2], v2[5] ) )//<<--<<--<<-- HERE IS THE PROBLEM
cout << v3[2] << " ist kleiner als " << v2[5] << endl;
int arr[5] = { 10, 5, 2, 3, 12 };
Vector v4;
cout << "v4: " << v4 << endl;
v4.setVector( arr, 4 );
cout << "v4 nach set: " << v4 << endl;
cout << "Minimum von v4: " << v4.min() << endl;
cout << "Anzahl von v4: " << v4.getAnzahl() << endl;
return 0;
}
vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
class Vector
{
int* v;
int anzahl;
public:
Vector(int anzahl = 10);
Vector( const Vector& vec ); // Kopierkonstruktor
~Vector();
friend bool kleiner( const int& a, const int& b );
int min() const;
int getAnzahl() const;
int operator[]( const int i ) const;
void setVector( int* sv, int sanzahl);
friend ostream& operator<< ( ostream& os, const Vector& v );
};
#endif
vector.cpp
#include "vector.h"
Vector::Vector( int a ) : anzahl(a)
{
v = new int[a];
for ( int i = 0; i < a; i++ )
v[i] = i;
}
Vector::Vector( const Vector& vec )
{
anzahl = vec.getAnzahl();
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = vec[i];
}
Vector::~Vector()
{
delete[] v;
v = NULL;
}
bool kleiner( const int& a, const int& b )
{
return ( a < b );
}
int Vector::min() const
{
int min = v[0];
for ( int i = 1; i < anzahl; i++ )
{
if ( v[i] < min )
min = v[i];
}
return min;
}
int Vector::getAnzahl() const
{
return anzahl;
}
int Vector::operator[] ( const int i ) const
{
return v[i];
}
void Vector::setVector( int* sv, int sanzahl )
{
delete[] v; // alten Inhalt loeschen
anzahl = sanzahl;
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = sv[i];
return;
}
ostream& operator<< ( ostream& os, const Vector& v )
{
for ( int i = 0; i < v.anzahl; i++ )
os << v[i] << ", ";
return os;
}
在類之外聲明該函數,並指定為朋友。
參考; http://en.cppreference.com/w/cpp/language/friend
首先在類或類模板X的朋友聲明中聲明的名稱成為X的最內層封閉名稱空間的成員,但不可用於查找(考慮X的依賴於參數的查找除外),除非名稱空間范圍內的匹配聲明為提供-有關詳細信息,請參見名稱空間。
我認為您和您的教授有不同的編譯器?
在標頭中的類定義之外也聲明Friend函數。 直到將其在類外聲明之前,它才可見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.