簡體   English   中英

C ++中的const_cast-獲取錯誤

[英]const_cast in c++ -getting errors

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

class Foo{
public:
    void func()
    {
        cout<<"Hello!!"<<endl;
    }
};

void some_func(const Foo &f)
{
    //f.func();
    Foo &fr=const_cast<Foo&>(f);
    fr.func();
}
int main()
{
    some_func(Foo &f); //if const declared will add the no of errors from 2 to 3
    return 0;
}

如何調用some_func(const Foo&f)...如果我在main中的Foo參數之前聲明const,則會顯示錯誤...但是,如果我使用上述代碼,則會出現2個錯誤。

輸出:

1>------ Build started: Project: const_cast, Configuration: Debug Win32 ------
1>Compiling...
1>const_cast.cpp
1>c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(24) : error C2065: 'f' : undeclared identifier
1>c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(24) : error C2275: 'Foo' : illegal use of this type as an expression
1>        c:\documents and settings\beata\my documents\visual studio 2008\projects\const_cast\const_cast\const_cast.cpp(8) : see declaration of 'Foo'
1>Build log was saved at "file://c:\Documents and Settings\beata\My Documents\Visual Studio 2008\Projects\const_cast\const_cast\Debug\BuildLog.htm"
1>const_cast - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

您的問題可能與main()

int main()
{
    Foo f;
    some_func(f);
    return 0;
}

您必須先聲明f才能使用它。

int main()
{
    Foo f;
    some_func(f);
    return 0;
}

some_func(Foo &f); 看起來像一個聲明,就像一個函數調用。 如果要進行函數調用,則只需將適當類型的對象傳遞給函數。 例如

Foo f;
some_func(f);

或如果您想傳遞未命名的臨時名稱(合法,因為該函數采用const引用):

some_func(Foo());

您看到的問題是您尚未將func函數調用標記為const ,以向編譯器指示其未修改可見狀態。 那是,

class Foo{
public:
    void func() const{
        std::cout << "Hello World!" << std::end;
    }
};

會很好的工作。 您可以在不修改狀態時將const放在函數調用的末尾(不完全正確,但對於本文更高級)。

因此,如果要通過const ref傳遞對象,則只能調用已聲明為非狀態修改的方法。 除非絕對必要,否則請不要使用const_cast

另外,不要忘記在主體中聲明Foo類型的變量。

some_func(Foo &f); //if const declared will add the no of errors from 2 to 3

語法錯誤。

這是您應該做的事情:

Foo f; //f is an object of type Foo
some_func(f); //pass the object to the function.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM