[英]void() issue - It doesn't print results
我正在編寫一個分為三個文件的程序:
my.h
的標頭; my.cpp
源cpp文件; use.cpp
; 在這里他們的陳述:
/* Header file my.h
Define global variable foo and functions print and print_foo
to print results out */
extern int foo;
void print_foo();
void print(int);
/* Source file my.cpp where are defined the two funcionts print_foo() and print()
and in where it is called the library std_lib_facilities.h */
#include "stdafx.h"
#include "std_lib_facilities.h"
#include "my.h"
void print_foo() {
cout << "The value of foo is: " << foo << endl;
return;
}
void print(int i) {
cout << "The value of i is: " << i << endl;
return;
}
/ use.cpp : definisce il punto di ingresso dell'applicazione console.
//
#include "stdafx.h"
#include "my.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int foo = 7;
int& i = foo;
i = 99;
char cc = '0';
while (cin >> cc) {
switch (cc) {
case '1':
void print_foo();
break;
case '2':
void print();
break;
default:
exit(EXIT_FAILURE);
}
}
return 0;
}
我的主要問題是程序可以正確編譯並運行,但沒有像我想象的那樣打印任何內容。
我該如何解決?
謝謝!
獅子座
不需要調用指定返回類型的函數。 正確
void print_foo(); // This actually declares a function prototype
至
print_foo();
和
print(i); // Pass i as argument
從void print_foo();
刪除void
void print_foo();
並void print();
在switch
塊中。
當前,您只是在聲明一個函數原型 ; 實際上沒有調用該函數。
您的extern int foo;
這種方法雖然在語法上有效,但會使您的代碼庫難以擴展和維護:請考慮顯式傳遞參數。
您的代碼聲明*“定義全局變量foo ...”,如下所示...
extern int foo;
...但是這只是聲明某個翻譯單元將實際定義它(沒有前導extern
限定詞)。 您發布的代碼中沒有實際的變量,這意味着您的程序不應鏈接,除非您正在巧用的某個庫中包含foo
符號。
此較短的代碼簡化了您的問題:
#include <iostream>
extern int foo;
void f()
{
std::cout << foo << '\n';
}
int main() {
int foo = 7;
f();
}
您可以在此處看到編譯器錯誤消息,即:
/tmp/ccZeGqgN.o: In function `f()':
main.cpp:(.text+0x6): undefined reference to `foo'
collect2: error: ld returned 1 exit status
您將輸入主函數
case '1':
print_foo();
break;
注意,在情況1中,我刪除了“ void”一詞。因為您沒有在那里重新聲明函數。 您只需要使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.